package com.elite.groovy.callback

import com.elite.groovy.kh.KHUtil
import com.elite.groovy.kh.LogToDB
import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.IpAddressUtil
import com.elite.groovy.util.Util
import net.sf.json.JSONObject
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

class apiIVRSendSMS implements ServiceBackInvoke {
    private static final Logger log = LoggerFactory.getLogger(apiIVRSendSMS.class);
    // 存储字符串映射关系的Map
    private Map<String, String> ivrSMS_Maps = new HashMap<>();

    String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        long startTime = System.currentTimeMillis();
        JSONObject res_Json = JSONObject.fromObject("{\"code\":1,\"msg\":\"提交成功\"}");

        String request_IP = IpAddressUtil.getIpAddress(request);

        String getMethod = request.getMethod();
        log.debug("apiIVRSendSMS getMethod:" + getMethod + " IP:" + request_IP);

        // 记录请求头信息
        Map<String, String> headerMap = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            log.debug("请求头 - {}: {}", key, value);
            headerMap.put(key, value);
        }

        // 记录请求参数信息
        Map<String, String> paramMap = new HashMap<String, String>();
        Enumeration paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String key = (String) paramNames.nextElement();
            String value = request.getParameter(key);
            log.debug("请求参数 - {}: {}", key, value);
            paramMap.put(key, value);
        }

        // 获取调用数据
        String callBody = Util.getRequestBody(request, "UTF-8");
        log.info("接收调用 POST 参数信息：" + callBody);

        // 该部分维护IVR中使用的模板内容和实际模板(因为IVR流程不好改)
        ivrSMS_Maps.put("尊敬的客户，您好！为了更好地为您提供服务，请点击以下链接在线填写咨询内容，我们将在1个工作日内安排专属客服为您服务。https://ccc.davco.cn/ngs/m/nl?b2uauqaa", "尊敬的客户，您好！为了更好地为您提供服务，请点击以下链接在线填写咨询内容，我们将在1个工作日内安排专属客服为您服务。https://ccc.davco.cn/m/com-davco/newwf#/");

        try {

            // 获取数据源
            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

            // 解析调用推送方式
            String apikey = GetMapV(paramMap, "apikey");
            String mobile = GetMapV(paramMap, "mobile");
            String text = GetMapV(paramMap, "text");
            String tag = GetMapV(paramMap, "tag");
            String noSign_text = removePrefixWithRegex(text).trim();
            log.info("接收" + tag + "调用 参数apikey：" + apikey + " mobile:" + mobile + " text:" + text + " noSign_text:" + noSign_text);

            // 检查IVR要发送的内容是否存在需要替换映射的模板配置
            String map_text = GetMapV(ivrSMS_Maps, noSign_text);
            text = KHUtil.isNull(map_text) ? text : text.replace(noSign_text, map_text);
            noSign_text = KHUtil.isNull(map_text) ? noSign_text : map_text;
            log.info("检查IVR要发送的内容是否存在需要替换映射的模板配置:" + map_text + " text:" + text + " noSign_text:" + noSign_text);

            // 固定发送75l7b0模板
            String querySQL = "Select Doctemplate_Id, Description, Documentpath, Documentpath2\n" +
                    "  From Doctemplate\n" +
                    " Where (Documentpath Like '%" + noSign_text + "%' Or\n" +
                    "       Documentpath2 Like '%" + noSign_text + "%')\n" +
                    "   And Check_Status = 'SUCCESS'\n" +
                    " Order By Case\n" +
                    "            When Documentpath Like '%【德高广州建材有限公司】%' Then\n" +
                    "             1\n" +
                    "            When Documentpath2 Like '%【德高广州建材有限公司】%' Then\n" +
                    "             2\n" +
                    "            When Description Like '%废除%' Then\n" +
                    "             999\n" +
                    "            Else\n" +
                    "             3\n" +
                    "          End,\n" +
                    "          Update_Time Desc Limit 1";

            List<Map<String, Object>> queryList = jt.queryForList(querySQL);

            if (queryList.size() > 0) {
                Map<String, Object> queryMap = queryList.get(0);
                String Doctemplate_Id = GetMapV(queryMap, "Doctemplate_Id");
                String Description = GetMapV(queryMap, "Description");
                String Documentpath = GetMapV(queryMap, "Documentpath");
                String Documentpath2 = GetMapV(queryMap, "Documentpath2");
                int send_Num = sendDataDB(eliteBean, '3', Documentpath.replaceAll("【西卡德高】", "【德高广州建材有限公司】"), text, "IVR-" + Description, "", "", "IVR", "匹配到模板" + apikey, mobile, Doctemplate_Id, "");

                res_Json.put("msg", "发送成功:" + send_Num);

            } else {
                sendDataDB(eliteBean, '3', text, text, "IVR-" + text, "", "", "IVR", "未匹配模板" + apikey, mobile, "/", "");
                res_Json.put("code", 0);
                res_Json.put("msg", "未匹配模板,使用text内容直接发送(大概率短信平台会返回失败)");
            }

        } catch (Exception e) {
            log.error("接口处理异常", e)
            res_Json.put("code", 0);
            res_Json.put("msg", "接口处理异常" + e.getMessage());
        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "提供天润IVR调用发送短信[" + request_IP + "]", "apiIVRSendSMS", paramMap.toString(), res_Json.toString(), "本次发送总耗时：" + (System.currentTimeMillis() - startTime).toString(), getMethod)
        }

        return res_Json;
    }

    // 添加document表，发送数据DB处理
    public static int sendDataDB(EliteBean eliteBean, String Doctype, String Documentpath, String Documentpath2, String Comments, String Customer_Guid, String Objective_Guid, String documentfrom, String Stringfield1, String documentto, String Template_Id, String linkURL) {
        long startTime = System.currentTimeMillis()
        log.debug("开始将发送内容数据处理到DB:" + startTime)
        int executeRow = 0
        try {
            def InsertSQL = "Insert Into Documentout" +
                    "  (Documentout_Guid," +
                    "   Doctype," +
                    "   Status," +
                    "   Trialcount," +
                    "   Trialcountlimit," +
                    "   Documentpath," +
                    "   Comments," +
                    "   Documentto," +
                    "   Priority_Id," +
                    "   Customer_Guid," +
                    "   Objective_Guid," +
                    "   Createdby," +
                    "   Createddate," +
                    "   documentfrom," +
                    "   Stringfield1," +
                    "   Documentpath2," +
                    "   Template_Id," +
                    "   Expectedstartdate," +
                    "   send_url)" +
                    "Values" +
                    "  (Uuid()," +
                    "   '" + Doctype + "'," +
                    "   0," +
                    "   0," +
                    "   3," +
                    "   '" + Documentpath + "'," +
                    "   '" + Comments + "'," +
                    "   '" + documentto + "'," +
                    "   '1'," +
                    "   '" + Customer_Guid + "'," +
                    "   '" + Objective_Guid + "'," +
                    "   'SELITE'," +
                    "   Now()," +
                    "   '" + documentfrom + "'," +
                    "   '" + Stringfield1 + "'," +
                    "   '" + Documentpath2 + "'," +
                    "   '" + Template_Id + "'," +
                    "   Now()," +
                    "   '" + linkURL + "')"
            executeRow = eliteBean.update(InsertSQL, "dataSource")

            long endTime = System.currentTimeMillis()
            log.debug("发送内容数据处理到DB时长(毫秒):" + (endTime - startTime))

        } catch (Exception e) {
            long endTime = System.currentTimeMillis()
            log.error("发送内容数据处理到DB时长(毫秒):" + (endTime - startTime) + " 处理失败(" + e.getMessage() + ")")
        }

        return executeRow
    }

    // 解析Mapn值(此方法增加需要解析的key不存在保护)
    static String GetMapV(Map inMap, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = String.valueOf(inMap.get(getKey));
        } catch (Exception e) {

            Rev_Value = "";
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            }
        }
        return Rev_Value;
    }

    /**
     * 使用正则表达式移除字符串开头的【...】标记
     * @param str 原始字符串
     * @return 移除标记后的字符串
     */
    public static String removePrefixWithRegex(String str) {
        // 检查字符串是否为空
        if (str == null || str.isEmpty()) {
            return str;
        }

        // 正则表达式：匹配以【开头，以】结尾的开头标记
        // ^表示字符串开始，【和】是标记的边界，.*?表示非贪婪匹配任意字符
        String regex = "^【.*?】";

        // 替换匹配到的内容为空字符串
        return str.replaceFirst(regex, "");
    }
}